<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农通 - AI问答</title>
    <link rel="icon" href="./assets/logo.ico" type="images/x-ico" />
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* AI问答页面特定样式 */
        .chat-container {
            display: flex;
            flex-direction: column;
            height: calc(100vh - 150px);
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .chat-header {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .chat-header h2 {
            color: #4CAF50;
            font-size: 24px;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #e0e0e0;
        }
        
        .message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
        }
        
        .message-user {
            align-self: flex-end;
            background-color: #e3f2fd;
            padding: 10px 15px;
            border-radius: 18px 18px 0 18px;
            max-width: 80%;
            margin-left: 20%;
        }
        
        .message-ai {
            align-self: flex-start;
            background-color: #f1f8e9;
            padding: 10px 15px;
            border-radius: 18px 18px 18px 0;
            max-width: 80%;
            margin-right: 20%;
        }
        
        .message-meta {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .chat-input-container {
            display: flex;
            gap: 10px;
        }
        
        .chat-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 24px;
            font-size: 14px;
            resize: none;
            height: 50px;
            transition: border-color 0.3s;
        }
        
        .chat-input:focus {
            border-color: #4CAF50;
            outline: none;
        }
        
        .send-button {
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 24px;
            padding: 0 20px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .send-button:hover {
            background-color: #3d8b40;
        }
        
        .send-button i {
            margin-right: 5px;
        }
        
        .typing-indicator {
            display: none;
            color: #666;
            font-size: 14px;
            margin-top: 5px;
        }
        
        .chat-history {
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 15px;
        }
        
        .history-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #333;
        }
        
        .history-list {
            display: flex;
            gap: 10px;
            overflow-x: auto;
            padding-bottom: 10px;
        }
        
        .history-item {
            background-color: #f5f5f5;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            white-space: nowrap;
            transition: background-color 0.3s;
        }
        
        .history-item:hover {
            background-color: #e0e0e0;
        }
        
        .history-item.active {
            background-color: #4CAF50;
            color: white;
        }

        .message-ai div:empty {
    padding: 0;
    background-color: transparent;
    border-radius: 0;
}
 
.message-ai:empty {
    margin-bottom: 0;
    padding: 0;
}

        .chat-messages {
    /* 确保包含以下属性 */
    overflow-anchor: none; /* 禁用浏览器自动滚动锚定 */
    contain: content; /* 优化浏览器渲染 */
}

.message:last-child {
    overflow-anchor: auto; /* 允许最后一个消息作为锚点 */
    margin-bottom: 0;
}
    </style>
</head>
<body>
<div class="admin-container">
    <!-- 侧边栏 - 更新后包含AI问答 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <img src="assets/logo.png" alt="惠农通">
                <h2>惠农通</h2>
            </div>
        </div>
        <nav class="sidebar-menu">
            <ul>
                <li data-page="dashboard">
                    <i class="fas fa-chart-line"></i>
                    <span>数据概览</span>
                </li>
                <li data-page="employees">
                    <i class="fas fa-users"></i>
                    <span>员工管理</span>
                </li>
                <li  data-page="expert">
                    <i class="fas fa-user-tie"></i>
                    <span>专家管理</span>
                </li>
                <li  data-page="farm-management">
                    <i class="fas fa-warehouse"></i>
                    <span>农场管理</span>
                </li>
                <li data-page="products">
                    <i class="fas fa-box-open"></i>
                    <span>产品管理</span>
                </li>
                <li data-page="order">
                    <i class="fas fa-shopping-cart"></i>
                    <span>订单管理</span>
                </li>
                <li class="active" data-page="ai-chat">
                    <i class="fas fa-robot"></i>
                    <span>AI问答</span>
                </li>
                <li data-page="activities">
                    <i class="fas fa-tractor"></i>
                    <span>农业活动</span>
                </li>
                <li data-page="settings">
                    <i class="fas fa-cog"></i>
                    <span>系统设置</span>
                </li>
            </ul>
        </nav>
        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
            </button>
        </div>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
        <header class="main-header">
            <h1 id="pageTitle">AI问答</h1>
            <div class="user-info">
                <span class="welcome">欢迎，<span id="currentUser">管理员</span></span>
                <div class="avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
            </div>
        </header>

        <!-- AI问答页面内容 -->
        <div class="page-content">
            <div class="chat-container">
                <div class="chat-header">
                    <h2>农业智能助手</h2>
                    <p>您可以在这里咨询任何关于农业的问题</p>
                </div>
                
                <div class="chat-messages" id="chatMessages">
                    <!-- 消息将在这里动态添加 -->
                    <div class="message">
                        <div class="message-ai">
                            您好！我是农业智能助手，可以为您解答各种农业相关问题，包括种植技术、病虫害防治、农产品市场信息等。请问有什么可以帮您的？
                            <div class="message-meta">AI助手 · 刚刚</div>
                        </div>
                    </div>
                </div>
                
                <div class="typing-indicator" id="typingIndicator">
                    <i class="fas fa-circle-notch fa-spin"></i> AI正在思考...
                </div>
                
                <div class="chat-input-container">
                    <textarea class="chat-input" id="chatInput" placeholder="输入您的问题..."></textarea>
                    <button class="send-button" id="sendButton">
                        <i class="fas fa-paper-plane"></i> 发送
                    </button>
                </div>
                
                <div class="chat-history">
                    <div class="history-title">历史对话</div>
                    <div class="history-list" id="historyList">
                        <!-- 历史对话将在这里动态添加 -->
                        <div class="history-item active">新对话</div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    // 基础URL配置
    const BASE_URL = 'http://192.168.8.128:8080';
    const token = localStorage.getItem('token');
    
    document.addEventListener('DOMContentLoaded', function() {
        // 设置当前活动菜单项
        function setActiveMenuItem() {
            const currentPage = 'ai-chat'; // 当前页面标识
            
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-page') === currentPage) {
                    item.classList.add('active');
                }
            });
        }
        
        // 页面跳转函数
        function navigateToPage(page) {
            if (page === 'dashboard') {
                window.location.href = 'dashboard.html';
            } else if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'products') {
                window.location.href = 'product.html';
            } else if (page === 'ai-chat') {
                window.location.href = 'ai-chat.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            }else if(page === 'expert'){
                window.location.href = 'expert.html';
            }else if(page === 'order'){
                window.location.href = 'order.html';
            }else if(page === 'farm-management'){
                window.location.href = 'farm.html';
            }
        }
        
        // 添加用户消息到聊天界面
        function addUserMessage(message) {
            scrollToBottom();
            const chatMessages = document.getElementById('chatMessages');
            const messageElement = document.createElement('div');
            messageElement.className = 'message';
            messageElement.innerHTML = `
                <div class="message-user">
                    ${message}
                    <div class="message-meta">${getCurrentTime()}</div>
                </div>
            `;
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 添加AI消息到聊天界面
        function addAiMessage(message) {
            const chatMessages = document.getElementById('chatMessages');
            const messageElement = document.createElement('div');
            messageElement.className = 'message';
            messageElement.innerHTML = `
                <div class="message-ai">
                    ${message}
                    <div class="message-meta">AI助手 · ${getCurrentTime()}</div>
                </div>
            `;
            chatMessages.appendChild(messageElement);
            scrollToBottom();
        }
        
        // 滚动到聊天底部
        function scrollToBottom() {
    const chatMessages = document.getElementById('chatMessages');
    // 使用多种方式确保滚动到底部
    setTimeout(() => {
        chatMessages.scrollTop = chatMessages.scrollHeight;
        chatMessages.scrollTo({
            top: chatMessages.scrollHeight,
            behavior: 'smooth'
        });
        // 双重确认
        requestAnimationFrame(() => {
            chatMessages.scrollTop = chatMessages.scrollHeight;
        });
    }, 100); // 稍微延迟确保DOM更新完成
}
        
        // 获取当前时间
        function getCurrentTime() {
            const now = new Date();
            return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        }


        async function sendMessage() {
    const chatInput = document.getElementById('chatInput');
    const message = chatInput.value.trim();
    
    if (!message) return;
    
    addUserMessage(message);
    chatInput.value = '';
    
    const typingIndicator = document.getElementById('typingIndicator');
    typingIndicator.style.display = 'block';
    scrollToBottom(); // 发送后立即滚动
    
    try {
        const chatId = 'chat-' + Date.now();
        const response = await fetch(`${BASE_URL}/ai/chat?prompt=${encodeURIComponent(message)}&chatId=${chatId}`,{
            headers: {
                'Authorization': `Bearer ${token}`,
            }
        });
        
        if (!response.ok) throw new Error('网络响应不正常');
        
        // 创建消息容器
        const messageElement = document.createElement('div');
        scrollToBottom();
        messageElement.className = 'message';
        messageElement.innerHTML = `
            <div class="message-ai">
                <div id="aiMessageContent"></div>
                <div id="aiMessageMeta" class="message-meta"></div>
            </div>
        `;
        document.getElementById('chatMessages').appendChild(messageElement);
        scrollToBottom(); // 添加容器后滚动
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let aiResponse = '';
        
        while (true) {
            const { done, value } = await reader.read();
            if (done) {
                document.getElementById('aiMessageMeta').textContent = `AI助手 · ${getCurrentTime()}`;
                scrollToBottom(); // 完成时滚动
                break;
            }
            
            const chunk = decoder.decode(value, { stream: true });
            aiResponse += chunk;
            document.getElementById('aiMessageContent').innerHTML = aiResponse;
            
            // 节流滚动，避免过于频繁
            if (Math.random() > 0.7) scrollToBottom(); 
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        addAiMessage("网络连接超时，请稍后再试");
    } finally {
        typingIndicator.style.display = 'none';
        scrollToBottom(); // 最终确保滚动
    }
}


        
        // 初始化页面
        function initPage() {
            setActiveMenuItem();
            
            // 添加菜单点击事件
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.addEventListener('click', function() {
                    const page = this.getAttribute('data-page');
                    console.log('点击了菜单项：', page);
                    navigateToPage(page);
                });
            });
            
            // 发送按钮点击事件
            document.getElementById('sendButton').addEventListener('click', sendMessage);
            
            // 输入框回车事件
            document.getElementById('chatInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    sendMessage();
                }
            });
            
            // 初始滚动到底部
            scrollToBottom();
        }
        
        // 初始化页面
        initPage();
    });
</script>
</body>
</html>